package com.exam.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.exam.dao.UserDao;
import com.exam.model.Role;
import com.exam.model.User;
import com.exam.service.IRoleService;
import com.exam.service.IUserService;
import com.exam.utils.ApplicationUtils;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 * 
 * @author weirdor
 * @since 2017-06-15
 */
@Controller
public class UserController extends BaseController {
	private static final Logger logger = LoggerFactory
			.getLogger(UserController.class);

	private final IUserService userService;
   private final IRoleService roleService;
	@Autowired
	public UserController(IUserService userService,IRoleService roleService) {
		this.userService = userService;
		this.roleService=roleService;
	}
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(ModelAndView modelAndView) {
		modelAndView.setViewName("login");
		return modelAndView;
	}

	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView,HttpServletRequest request,@RequestParam(required = false) Integer pageNumber) {
		    modelAndView.setViewName("index");
		     if(pageNumber==null){
		    	 pageNumber=1;
		     }
		    Page<User> page=userService.selectUserPage(new Page<User>(pageNumber,15));
	        modelAndView.addObject("userList", page.getRecords());
	        System.err.println(page.getRecords());
	        modelAndView.addObject("page",page);
	        HttpSession session=request.getSession();
	        User user=userService.selectUser(session.getAttribute("username").toString());
	      
	        modelAndView.addObject("user",user);
		return modelAndView;
	}

	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public Object login(User user, ModelAndView modelAndView) {
		Map<String, Object> map = new HashMap<String, Object>();
		modelAndView.setViewName("index");
		String username = user.getUsername();
		String password = user.getPassword();
		password = ApplicationUtils.md5Hex(password);
		logger.debug("username => " + username);
		logger.debug("password => " + password);
		UsernamePasswordToken token = new UsernamePasswordToken(username,
				password);
		token.setRememberMe(true);
		Subject subject = SecurityUtils.getSubject();
		try {

			subject.login(token);
			// 验证是否登录成功
			if (subject.isAuthenticated()) {
				System.out.println("用户[" + username
						+ "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
				map.put("url", "/index");
			} else {
				token.clear();
			}
		} catch (UnknownAccountException uae) {
			System.out.println("对用户[" + username + "]进行登录验证..验证未通过,未知账户");
			map.put("message_login", "未知账户");
		} catch (IncorrectCredentialsException ice) {
			System.out.println("对用户[" + username + "]进行登录验证..验证未通过,错误的凭证");
			map.put("message_login", "密码不正确");
		} catch (LockedAccountException lae) {
			System.out.println("对用户[" + username + "]进行登录验证..验证未通过,账户已锁定");
			map.put("message_login", "账户已锁定");
		} catch (ExcessiveAttemptsException eae) {
			System.out.println("对用户[" + username + "]进行登录验证..验证未通过,错误次数过多");
			map.put("message_login", "用户名或密码错误次数过多");
		} catch (AuthenticationException ae) {
			// 通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
			System.out.println("对用户[" + username + "]进行登录验证..验证未通过,堆栈轨迹如下");
			ae.printStackTrace();
			map.put("message_login", "用户名或密码不正确");
		}

		return map;

	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public ModelAndView logout(ModelAndView modelAndView) {
		modelAndView.setViewName("login");
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		System.out.println("您已经退出登录");
		return modelAndView;
	}

	@RequestMapping(value = "/regist", method = RequestMethod.POST)
	public @ResponseBody
	Object regist(User user) {
		String username = user.getUsername();
		String password = user.getPassword();
		password = ApplicationUtils.md5Hex(password);
		user.setPassword(password);
		EntityWrapper<User> ew = new EntityWrapper<User>();
		ew.setEntity(new User());
		ew.where("username = {0}", username);
		User use = userService.selectByUsername(ew);
		if (use == null) {
			user.setCreateTime(new Date());
			user.setRoleld("2");
			return userService.insert(user) ? renderSuccess("注册成功")
					: renderError("注册失败");
		} else {
			return renderError("账户已经存在");
		}
	}
	@ResponseBody
	@RequestMapping("/del")
    public Object del(@RequestParam(required = true) Long id) {
        System.out.println(id);
        Map<String, Object> map = new HashMap<String, Object>();
        if(userService.deleteById(id)){
        	
        	  map.put("resul", 1);
        }
        else{
        	map.put("resul", 2);
        }
        return map;
    }
	@RequestMapping( value="/edit", method = RequestMethod.GET)
    public Object editt(@RequestParam(required = true) Long id, ModelAndView modelAndView) {
        System.out.println(id);
        modelAndView.setViewName("ed");
        User user=userService.selectUserId(id);
        List<Role> role=roleService.selectList(null);
        modelAndView.addObject("user",user);
        modelAndView.addObject("role",role);
        return modelAndView;
    }
	@ResponseBody
	@RequestMapping( value="/edit", method = RequestMethod.POST)
    public 	 Object edit(User user,ModelAndView modelAndView) {
		 modelAndView.setViewName("ed");
		 Map<String, Object> map = new HashMap<String, Object>();
		System.out.println(user);
		System.out.println(user.getPassword());
		  if(user.getPassword()!=null){
				user.setPassword(ApplicationUtils.md5Hex(user.getPassword()));
		  }
		if(userService.updateById(user)){
			
      	  map.put("resul", 1);
      }
      else{
      	map.put("resul", 2);
      }
      return map;
    }
}
